import React, { useEffect, useState } from 'react'
import { Form, Input, message, Radio, Upload, Icon, Select, Button } from 'antd'
import { getProductDetail, updateProduct, addProduct, getChannelList } from '../../../request/product'
import Cookies from 'js-cookie'
import { withRouter } from 'react-router-dom'
import { TOKEN_KEY } from '../../../constants'
import { connect } from 'react-redux'
import { actionCreators } from '../../../store'
import { formItemLayout } from '../../const'
import ColorSelect from './ColorSelectDialog'
import { getUserList } from '../../../request/setting'
import './style.scss'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

function EditProduct(props) {
  const { setBreadcrumb } = props
  const { getFieldDecorator, validateFields } = props.form
  const [headImgUrl, setHeadImgUrl] = useState('')
  const [tailImgUrl, setTailImageUrl] = useState('')
  const [formData, setFormData] = useState({})
  const [isHeadUploadLoading, setIsHeadUploadLoading] = useState(false)
  const [isTailUploadLoading, setIsTailUploadLoading] = useState(false)
  const [isBtnLoading, setIsBtnLoading] = useState(false)
  const [h5PageColor, setH5PageColor] = useState('#202342')
  const [isShowColorSelect, setIsShowColorSelect] = useState(false)
  const [channelList, setChannelList] = useState([])
  const [agentList, setAgentList] = useState([])
  const TOKEN = Cookies.get(TOKEN_KEY)
  const { Item } = Form

  useEffect(() => {
    const id = props.match.params.id
    setBreadcrumb([
      { name: '在售商品', path: '/product/list' },
      { name: id ? '编辑商品' : '新增商品' }
    ])
    getAllChannel().catch(e => console.log(e.message))
    getAgentList().catch(e => console.log(e.message))
    if (id) {
      getProduct(Number(id)).catch(e => console.log(e.message))
    }
  }, [])

  useEffect(() => {
    if (formData.head_img_url) {
      setHeadImgUrl(formData.head_img_url)
    }
    if (formData.tail_img_url) {
      setTailImageUrl(formData.tail_img_url)
    }
  }, [formData.head_img_url, formData.tail_img_url])

  const getProduct = async(id) => {
    const { code, message: errMsg, data } = await getProductDetail({ id })
    if (code) {
      message.error(errMsg)
      return false
    }
    if (data.bg_color) {
      setH5PageColor(data.bg_color)
    }
    setFormData(data)
  }

  const getAgentList = async() => {
    const { code, message: errMsg, data } = await getUserList({ role_id: 23, valid: 1, size: 1000 })
    if (code) {
      return message.error(errMsg)
    }
    setAgentList(data.list)
  }

  const getAllChannel = async() => {
    const { code, message: errMsg, data } = await getChannelList()
    if (code) {
      message.error(errMsg)
      return false
    }
    setChannelList(data)
  }

  const onSubmit = () => {
    validateFields(async(err, values) => {
      if (err) {
        return false
      }
      if (values.user_id) {
        const agent = agentList.find(item => item.id === values.user_id)
        if (agent) {
          values.user_name = agent.actual_name
        }
      } else {
        formData.user_name = values.user_name = ''
        formData.user_id = values.user_id = 0
      }
      const data = { ...formData, ...values, bg_color: h5PageColor }
      setIsBtnLoading(true)
      const res = formData.id ? await updateProduct(data) : await addProduct(data)
      setIsBtnLoading(false)
      if (res.code) {
        message.error(res.message)
        return false
      }
      message.success(formData.id ? '修改成功' : '添加成功')
      if (!formData.id) {
        props.history.push('/product/list')
      }
    })
  }

  const headUploadButton = (
    <div>
      <Icon type={isHeadUploadLoading ? 'loading' : 'plus'}/>
      <div className="ant-upload-text">点击上传</div>
    </div>
  )

  const tailUploadButton = (
    <div>
      <Icon type={isTailUploadLoading ? 'loading' : 'plus'}/>
      <div className="ant-upload-text">点击上传</div>
    </div>
  )

  const handleChange = (info, type) => {
    if (info.file.status === 'uploading') {
      type === 'head' ? setIsHeadUploadLoading(true) : setIsTailUploadLoading(true)
      return
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imgUrl => {
        type === 'head' ? setHeadImgUrl(imgUrl) : setTailImageUrl(imgUrl)
      })
    }
    const res = info.file.response
    if (res.code) {
      message.error(res.message)
    }
    const typeMap = { head: 'head_img_url', tail: 'tail_img_url' }
    setFormData({ ...formData, [typeMap[type]]: res.data[0].addr })
  }

  return (
    <div className="product-edit">
      <Form {...formItemLayout}>
        <h3>商品编辑</h3>
        <Item label="产品渠道">
          {getFieldDecorator('partner_id', {
            initialValue: formData.partner_id,
            rules: [
              { required: true, message: '渠道不能为空' }
            ]
          })(
            <Select>
              {channelList.map(item => (
                <Select.Option label={item.name} key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
            </Select>
          )}
        </Item>
        <Item label="商品名称">
          {getFieldDecorator('name', {
            initialValue: formData.name,
            rules: [
              { required: true, message: '套餐名称不能为空' }
            ]
          })(
            <Input placeholder="请输入套餐名称"/>
          )}
        </Item>
        <Item label="页面名称">
          {getFieldDecorator('page_name', {
            initialValue: formData.page_name,
            rules: [
              { required: true, message: '页面名称不能为空' }
            ]
          })(
            <Input placeholder="请输入页面餐名称（H5页面标题）"/>
          )}
        </Item>
        <Item label="所属代理商">
          {getFieldDecorator('user_id', {
            initialValue: formData.user_id || undefined
          })(
            <Select allowClear={true} placeholder="请选择所属代理商">
              {agentList.map(item => (
                <Select.Option label={item.actual_name} key={item.id} value={item.id}>{item.actual_name}</Select.Option>
              ))}
            </Select>
          )}
        </Item>
        <Item label="京东特有(必须三位)">
          {getFieldDecorator('jd_code', {
            initialValue: formData.jd_code
          })(
            <Input placeholder="请输入京东特有抓单码"/>
          )}
        </Item>
        <Item label="商品卖点">
          {getFieldDecorator('sell_point', {
            initialValue: formData.sell_point
          })(
            <Input placeholder="商品卖点"/>
          )}
        </Item>
        <Item label="URL额外参数">
          {getFieldDecorator('url_param', {
            initialValue: formData.url_param
          })(
            <Input placeholder="链接额外参数"/>
          )}
        </Item>
        <Item label="H5页面背景色">
          <div>
            <div
              className="color-select"
              style={{ backgroundColor: h5PageColor }}
              onClick={() => setIsShowColorSelect(true)}
            >
            </div>
            <div className="color-result">{h5PageColor}</div>
          </div>
        </Item>
        <Item label="是否启用短信">
          {getFieldDecorator('sms_flag', {
            initialValue: formData.sms_flag,
            rules: [
              { required: true, message: '选择是否启用短信' }
            ]
          })(
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          )}
        </Item>
        <Item label="身份证号初始显示">
          {getFieldDecorator('idcard_display', {
            initialValue: formData.idcard_display,
            rules: [
              { required: true, message: '选择身份证号是否初始显示' }
            ]
          })(
            <Radio.Group>
              <Radio value={1}>显示</Radio>
              <Radio value={0}>不显示</Radio>
            </Radio.Group>
          )}
        </Item>
        <Item label="是否显示备案信息">
          {getFieldDecorator('icp_flag', {
            initialValue: formData.icp_flag,
            rules: [
              { required: true, message: '选择是否显示备案信息' }
            ]
          })(
            <Radio.Group>
              <Radio value={1}>显示</Radio>
              <Radio value={0}>不显示</Radio>
            </Radio.Group>
          )}
        </Item>
        <Item label="备案号">
          {getFieldDecorator('icp', {
            initialValue: formData.icp
          })(
            <Input.TextArea rows={4} placeholder="备案号，如：浙ICP备17017272号-1"/>
          )}
        </Item>
        <Item label="页面顶图">
          <Upload
            name="file"
            listType="picture-card"
            showUploadList={false}
            action={'/v1/bk/market/oss-market/upload'}
            onChange={info => {
              handleChange(info, 'head')
            }}
            headers={{ token: TOKEN }}
          >
            <div style={{ width: '375px' }}>
              {headImgUrl ? <img src={headImgUrl} alt="avatar" style={{ width: '100%' }}/> : headUploadButton}
            </div>
          </Upload>
          {headImgUrl && (
            <a
              onClick={() => {
                setHeadImgUrl('')
                setFormData({ ...formData, head_img_url: '' })
              }}
            >
              移除顶图
            </a>
          )}
        </Item>
        <Item label="页面底图">
          <Upload
            name="file"
            listType="picture-card"
            showUploadList={false}
            action={'/v1/bk/market/oss-market/upload'}
            onChange={info => {
              handleChange(info, 'tail')
            }}
            headers={{ token: TOKEN }}
          >
            <div style={{ width: '375px' }}>
              {tailImgUrl ? <img src={tailImgUrl} alt="avatar" style={{ width: '100%' }}/> : tailUploadButton}
            </div>
          </Upload>
          {tailImgUrl && (
            <a onClick={() => {
              setTailImageUrl('')
              setFormData({ ...formData, tail_img_url: '' })
            }}>移除底图</a>
          )}
        </Item>
        <Item label="描述">
          {getFieldDecorator('detail', {
            initialValue: formData.detail,
            rules: [
              { required: true, message: '描述不能为空' }
            ]
          })(
            <Input.TextArea rows={5} placeholder="请输入描述"/>
          )}
        </Item>
        <Item label=" " colon={false}>
          <Button type="primary" loading={isBtnLoading} onClick={onSubmit}>保存</Button>
        </Item>
      </Form>
      {isShowColorSelect && (
        <ColorSelect
          h5PageColor={h5PageColor}
          setH5PageColor={setH5PageColor}
          visible={isShowColorSelect}
          close={() => setIsShowColorSelect(false)}
        />
      )}
    </div>
  )
}

export default connect(null, dispatch => ({
  setBreadcrumb(value) {
    dispatch(actionCreators.setBreadCrumb(value))
  }
}))(Form.create()(withRouter(EditProduct)))
